<template>
  <div class="code-step-generator">
    <h2>代码分步生成工具</h2>
    
    <!-- 步骤指示器 -->
    <div class="step-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px;">
      <a-steps :current="currentStep" style="flex: 1;">
        <a-step title="需求文档解析" description="解析需求文档获取结构化数据" />
        <a-step title="Swagger文档匹配" description="为各区域指定Swagger文档并匹配字段" />
        <a-step title="区域页面代码配置&代码生成" description="生成对应的代码文件" />
      </a-steps>
      <div class="step-actions" style="margin-left: 20px;">
        <a-button 
          v-if="currentStep > 0" 
          @click="prevStep" 
          style="margin-right: 10px;"
        >
          上一步
        </a-button>
        <a-button 
          v-if="currentStep < 2" 
          type="primary" 
          @click="nextStep" 
          :disabled="!canNextStep"
          :title="getNextButtonTooltip"
        >
          下一步
        </a-button>
      </div>
    </div>

    <!-- 第一步：需求文档解析 -->
    <div v-if="currentStep === 0" class="step-content">
      <a-card title="需求文档解析" style="margin-bottom: 20px;">
        <a-form layout="vertical">
          <a-row :gutter="16">
            <a-col :span="16">
              <a-form-item label="需求文档地址">
                <a-input v-model:value="requirementForm.url" placeholder="请输入Confluence页面地址" />
              </a-form-item>
            </a-col>
            <a-col :span="8" style="display: flex; align-items: flex-end;">
              <a-button type="primary" @click="analyzeRequirement" :loading="loading">开始解析</a-button>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="Confluence 用户名">
                <a-input v-model:value="requirementForm.username" placeholder="默认: gushan" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="Confluence 密码">
                <a-input-password v-model:value="requirementForm.password" placeholder="默认: 123456" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>

      <!-- 解析结果 -->
      <div v-if="analysisResult">
        <a-alert
          v-if="analysisResult.pageTitle"
          :message="`解析成功: ${analysisResult.pageTitle}`"
          type="success"
          show-icon
          style="margin-bottom: 20px;"
        />

        <a-card title="结构化结果" style="margin-bottom: 20px;">
          <a-tabs v-model:activeKey="activeTab">
            <a-tab-pane v-for="(areaData, areaName) in analysisResult.structure" :key="areaName" :tab="getAreaName(areaName)">
              <a-tabs type="card" size="small">
                <!-- 查询区域 -->
                <a-tab-pane v-if="areaData.search && areaData.search.length > 0" key="search" tab="查询条件">
                  <a-table 
                    :columns="analysisColumns" 
                    :data-source="areaData.search" 
                    :pagination="false" 
                    rowKey="label"
                    size="small"
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.key === 'required'">
                        <a-tag :color="record.required ? 'red' : 'green'">
                          {{ record.required ? '必填' : '非必填' }}
                        </a-tag>
                      </template>
                      <template v-if="column.key === 'defaultDisplay'">
                        <a-tag :color="record.isDefaultShow ? 'blue' : ''">
                          {{ record.isDefaultShow ? '是' : '否' }}
                        </a-tag>
                      </template>
                    </template>
                  </a-table>
                </a-tab-pane>

                <!-- 列表区域 -->
                <a-tab-pane v-if="areaData.table && areaData.table.length > 0" key="table" tab="列表字段">
                  <a-table 
                    :columns="analysisColumns" 
                    :data-source="areaData.table" 
                    :pagination="false" 
                    rowKey="label"
                    size="small"
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.key === 'required'">
                        <a-tag :color="record.required ? 'red' : 'green'">
                          {{ record.required ? '必填' : '非必填' }}
                        </a-tag>
                      </template>
                      <template v-if="column.key === 'defaultDisplay'">
                        <a-tag :color="record.isDefaultShow ? 'blue' : ''">
                          {{ record.isDefaultShow ? '是' : '否' }}
                        </a-tag>
                      </template>
                    </template>
                  </a-table>
                </a-tab-pane>

                <!-- 表单区域 -->
                <a-tab-pane v-if="areaData.form && areaData.form.length > 0" key="form" tab="表单字段">
                  <a-table 
                    :columns="analysisColumns" 
                    :data-source="areaData.form" 
                    :pagination="false" 
                    rowKey="label"
                    size="small"
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.key === 'required'">
                        <a-tag :color="record.required ? 'red' : 'green'">
                          {{ record.required ? '必填' : '非必填' }}
                        </a-tag>
                      </template>
                      <template v-if="column.key === 'defaultDisplay'">
                        <a-tag :color="record.isDefaultShow ? 'blue' : ''">
                          {{ record.isDefaultShow ? '是' : '否' }}
                        </a-tag>
                      </template>
                    </template>
                  </a-table>
                </a-tab-pane>
              </a-tabs>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </div>
    </div>

    <!-- 第二步：Swagger文档匹配 -->
    <div v-if="currentStep === 1" class="step-content">
        <!-- 字段匹配结果展示 -->
        <a-card title="字段匹配结果" style="margin-bottom: 20px;">
          <a-tabs v-model:activeKey="matchResultActiveTab">
            <a-tab-pane v-for="(areaData, areaName) in analysisResult.structure" :key="areaName" :tab="getAreaName(areaName)">
              <!-- 单一数据源字段匹配 -->
              <FieldMatcher 
                :ref="(el) => setFieldMatcherRef(el, areaName)"
                :fields="[...((areaData.search || [])), ...((areaData.table || [])), ...((areaData.form || []))]" 
                :area-name="areaName"
                :data-source="areaData"
                @field-matched="handleFieldMatched"
              />
            </a-tab-pane>
          </a-tabs>
        </a-card>
    </div>

    <!-- 第三步：代码生成 -->
    <div v-if="currentStep === 2" class="step-content">
      <a-card title="区域页面代码配置" style="margin-bottom: 20px;">
        <a-form layout="vertical">
          <!-- 动态区域PageCode配置 -->
          <a-row :gutter="16" v-if="analysisResult && analysisResult.structure">
            <a-col :span="8" v-for="(areaData, areaName) in analysisResult.structure" :key="areaName">
              <a-form-item :label="`${getAreaName(areaName)}页面代码`">
                <a-input 
                  v-model:value="codeGenForm.areaPageCodes[areaName]" 
                  :placeholder="`请输入${getAreaName(areaName)}的页面代码`"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>

      <div style="display: flex; justify-content: space-between;">
        <a-button @click="prevStep">上一步</a-button>
        <a-button type="primary" @click="showPreviewCode" :loading="generateLoading">
          <template #icon>
          <EyeOutlined />
          </template>
          预览并下载代码
        </a-button>
      </div>
    </div>
  </div>
  
  <!-- 代码预览弹窗 -->
  <CodePreviewModal 
    v-model:open="previewCodeVisible"
    :files="previewCodeFiles"
    @download-all="downloadGeneratedCode"
  />
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { message } from 'ant-design-vue';
import { EyeOutlined } from '@ant-design/icons-vue';
import { config } from '../config.js';
import FieldMatcher from '../components/FieldMatcher.vue';
import CodePreviewModal from '../components/CodePreviewModal.vue';

const currentStep = ref(0);
const loading = ref(false);
const codeGenLoading = ref(false);
const generateLoading = ref(false);
const activeTab = ref('');
const matchResultActiveTab = ref('');
const areaDataSources = ref({});

// 代码预览相关状态
const previewCodeVisible = ref(false);
const previewCodeFiles = ref([]);

// 表单数据
const requirementForm = reactive({
  url: 'http://192.168.2.200:8090/pages/viewpage.action?pageId=75667598',
  username: 'gushan',
  password: '123456'
});

const codeGenForm = reactive({
  moduleName: '',
  outputPath: '',
  options: ['vue', 'api', 'mock'],
  areaPageCodes: {} // 动态存储每个区域的pageCode
});

// 结果数据
const analysisResult = ref(null);
const codeGenResult = ref(null);

// 存储FieldMatcher组件实例
const fieldMatcherRefs = ref({});

// 监听analysisResult变化，确保字段匹配结果默认选中第一个区域
watch(() => analysisResult.value, (newValue) => {
  if (newValue && newValue.structure) {
    const firstArea = Object.keys(newValue.structure)[0];
    if (firstArea && !matchResultActiveTab.value) {
      matchResultActiveTab.value = firstArea;
    }
  }
}, { immediate: true });

// 分析结果表格列
const analysisColumns = [
  {
    title: '字段文字 (Label)',
    dataIndex: 'label',
    key: 'label',
    width: 150
  },
  {
    title: '必填',
    dataIndex: 'required',
    key: 'required',
    width: 80
  },
  {
    title: '组件类型',
    dataIndex: 'componentType',
    key: 'componentType',
    width: 120
  },
  {
    title: '默认显示',
    dataIndex: 'defaultDisplay',
    key: 'defaultDisplay',
    width: 100
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  }
];

// 获取区域名称
const getAreaName = (areaName) => {
  const areaMap = {
    header: '表头区域',
    body: '表体区域',
    search: '查询区域',
    table: '列表区域',
    form: '表单区域'
  };
  return areaMap[areaName] || areaName;
};

// 处理FieldMatcher组件的ref赋值
const setFieldMatcherRef = (el, areaName) => {
  if (el && fieldMatcherRefs.value) {
    fieldMatcherRefs.value[areaName] = el;
  }
};

// 需求文档解析
const analyzeRequirement = async () => {
  if (!requirementForm.url) {
    message.warning('请输入文档地址');
    return;
  }

  loading.value = true;
  
  try {
    const response = await fetch(`${config.domain}/api/analyze-requirement`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requirementForm)
    });

    const data = await response.json();

    if (data.success) {
      analysisResult.value = data.data;
      activeTab.value = Object.keys(data.data.structure)[0] || '';
      // 设置字段匹配结果的默认选中第一个区域
      matchResultActiveTab.value = Object.keys(data.data.structure)[0] || '';
      // 初始化区域数据源结构
      if (data.data.structure) {
        Object.keys(data.data.structure).forEach(areaName => {
          if (!areaDataSources.value[areaName]) {
            areaDataSources.value[areaName] = { queryFields: [], listFields: [] }
          }
        })
      }
      message.success('解析成功');
    } else {
      message.error(data.message || '解析失败');
    }
  } catch (error) {
    console.error('Analysis error:', error);
    message.error('解析请求失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 控制下一步按钮是否可点击
const canNextStep = computed(() => {
  switch (currentStep.value) {
    case 0: // 第一步：需求文档解析
      return analysisResult.value !== null; // 必须有解析结果
    case 1: // 第二步：Swagger文档匹配
      return true; // 必须配置数据源且完成匹配
    default:
      return false;
  }
});

// 获取下一步按钮的提示信息
const getNextButtonTooltip = computed(() => {
  if (canNextStep.value) {
    return '';
  }
  
  switch (currentStep.value) {
    case 0:
      return '请先完成需求文档解析';
    default:
      return '';
  }
});

// 步骤控制
const nextStep = () => {
  if (currentStep.value < 2) {
    currentStep.value++;
  }
};

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--;
  }
};

// 生成代码
const generateCode = async () => {
  if (!codeGenForm.moduleName || !codeGenForm.outputPath) {
    message.warning('请填写完整的生成配置');
    return;
  }

  // 检查是否至少有一个区域配置了页面代码
  const hasAreaPageCode = Object.keys(codeGenForm.areaPageCodes).some(key => codeGenForm.areaPageCodes[key]);
  if (!hasAreaPageCode) {
    message.warning('请至少为一个区域配置页面代码');
    return;
  }

  codeGenLoading.value = true;
  
  try {
    const response = await fetch(`${config.domain}/api/generate-code-step`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        analysisResult: analysisResult.value,
        config: codeGenForm
      })
    });

    const data = await response.json();
    codeGenResult.value = data;

    if (data.success) {
      message.success('代码生成成功');
    } else {
      message.error(data.message || '代码生成失败');
    }
  } catch (error) {
    console.error('Code generation error:', error);
    message.error('代码生成失败: ' + error.message);
  } finally {
    codeGenLoading.value = false;
  }
};

// 显示代码预览
const showPreviewCode = async () => {
  // 检查是否至少有一个区域配置了页面代码
  const hasAreaPageCode = Object.keys(codeGenForm.areaPageCodes).some(key => codeGenForm.areaPageCodes[key]);
  if (!hasAreaPageCode) {
    message.warning('请至少为一个区域配置页面代码');
    return;
  }
  
  if (!analysisResult.value) {
    message.warning('请先完成需求文档解析和字段匹配');
    return;
  }
  await previewCode();
};

// 预览代码函数
const previewCode = async () => {
  // 显示加载状态
  generateLoading.value = true;
  const fields = getFieldMatchingResults()
  try {
    // 组织请求数据
    const requestData = {
        pageCode: codeGenForm.areaPageCodes,
        generationType: 'list_detail',
        dataSourceConfig: {
          headerFields: fields.header.form,
          queryFields: fields.header.search,
          listFields: fields.header.table,
          detailListFields: fields.body.table,
          detailQueryFields: fields.body.search,
          detailFormFields: fields.body.form,
        }
      };    
    // 调用后端接口生成代码预览
    const response = await fetch(`${config.domain}/api/generate-code-preview`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    });
    
    const resultData = await response.json();
    
    if (resultData.success) {
      // 设置预览文件
      previewCodeFiles.value = resultData.files;
      
      // 显示预览弹窗
      previewCodeVisible.value = true;
      
      message.success('代码预览生成成功');
    } else {
      message.error(resultData.error || '代码预览生成失败');
    }
  } catch (error) {
    console.error('代码预览生成失败:', error);
    message.error('代码预览生成失败: ' + error.message);
  } finally {
    generateLoading.value = false;
  }
};

// 获取字段匹配结果，key值为areaName，value值为FieldMatcher组件的getCheckedFields出参
const getFieldMatchingResults = () => {
  const results = {};
  
  // 遍历所有FieldMatcher组件实例
  Object.keys(fieldMatcherRefs.value).forEach(areaName => {
    const fieldMatcherInstance = fieldMatcherRefs.value[areaName];
    
    // 检查组件实例是否存在且有getCheckedFields方法
    if (fieldMatcherInstance && typeof fieldMatcherInstance.getCheckedFields === 'function') {
      try {
        results[areaName] = fieldMatcherInstance.getCheckedFields();
      } catch (error) {
        console.error(`获取区域 ${areaName} 的字段匹配结果失败:`, error);
        results[areaName] = { search: [], table: [], form: [] };
      }
    } else {
      // 如果组件实例不存在或方法不可用，返回空数据
      results[areaName] = { search: [], table: [], form: [] };
    }
  });
  
  return results;
};


// 下载生成的代码
const downloadGeneratedCode = async () => {
  // 显示加载状态
  generateLoading.value = true
  const fields = getFieldMatchingResults()
  try {
    // 组织请求数据
    const requestData = {
        pageCode: codeGenForm.areaPageCodes,
        generationType: 'list_detail',
        dataSourceConfig: {
          headerFields: fields.header.form,
          queryFields: fields.header.search,
          listFields: fields.header.table,
          detailListFields: fields.body.table,
          detailQueryFields: fields.body.search,
          detailFormFields: fields.body.form,
        }
      }; 
    // 调用后端接口生成代码
    const response = await fetch(`${config.domain}/api/generate-code-from-data`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    })
    
    if (response.ok) {
      // 获取文件名
      const disposition = response.headers.get('Content-Disposition')
      let filename = 'generated-code.zip'
      if (disposition && disposition.indexOf('attachment') !== -1) {
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
        const matches = filenameRegex.exec(disposition)
        if (matches != null && matches[1]) {
          filename = matches[1].replace(/['"]/g, '')
        }
      }
      
      // 创建下载链接
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      // 提示成功
      message.success('代码生成成功')
    } else {
      const errorText = await response.text()
      console.error('代码生成失败:', errorText)
      message.error('代码生成失败: ' + errorText)
    }
  } catch (error) {
    console.error('代码生成失败:', error)
    message.error('代码生成失败: ' + error.message)
  } finally {
    generateLoading.value = false
  }
}

// 暴露方法给模板或其他组件使用
defineExpose({
  getFieldMatchingResults
});

</script>

<style scoped>
.code-step-generator {
  padding: 20px;
}

.step-header {
  background: #f5f5f5;
  padding: 16px 20px;
  border-radius: 8px;
  margin-bottom: 30px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.step-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.step-content {
  min-height: 600px;
}

:deep(.ant-steps-item-title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.ant-steps-item-description) {
  font-size: 14px;
}

:deep(.ant-steps-item-active .ant-steps-item-title) {
  color: #1890ff;
}

:deep(.ant-btn-primary:disabled) {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
